//
//  LZSCollectionViewController.m
//  IOSProject
//
//  Created by lzs on 2018/4/18.
//  Copyright © 2018年 com.linzhisheng. All rights reserved.
//

#import "LZSCollectionViewController.h"
#import "LZSOneCell.h"

#import "LZSTouTiaoModel.h"

#import "LZSFMDBManager.h"

#import "LZSArticelDetailViewController.h"
#import "LZSNoCollectionView.h"

@interface LZSCollectionViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong)  LZSNoCollectionView *cryview;
@end

@implementation LZSCollectionViewController

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的收藏";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorColor = [UIColor lightGrayColor];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //
    self.tableView.estimatedRowHeight = 80;
    
    self.tableView.separatorColor = [UIColor colorWithHexString:@"#c8c8c8"];
    
    //默认【下拉刷新】
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
//    //默认【上拉加载】
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    //
    self.tableView.tableFooterView = [UIView new];
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).mas_offset(0);
    }];
    
    LZSNoCollectionView *cryview = [[LZSNoCollectionView alloc] init];
    self.cryview = cryview;
    [self.view addSubview:cryview];
    cryview.hidden = YES;
    [cryview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).mas_offset(0);
    }];

    //读取整个表的数据
    __block NSMutableArray *allArr = [NSMutableArray array];
    
    NSDictionary *loginDic = [[NSUserDefaults standardUserDefaults]valueForKey:@"ISLOGIN"];
    
    [[LZSFMDBManager fmdbManager] readAllDataWithTableName:loginDic[@"name"] dataArr:^(NSArray *dataArr) {
        NSLog(@"dataArr%@",dataArr);
//       NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:dataArr[0] options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"dictionary%@",dictionary);
//        dataArr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (dataArr.count >0) {
            for (int i = 0; i<dataArr.count; i++) {
                NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:dataArr[i] options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"dictionary%@",dictionary);
                [allArr addObject:dictionary];
            }
            self.dataArray = [LZSListModel mj_objectArrayWithKeyValuesArray:allArr];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
                
                dispatch_async(dispatch_get_main_queue(), ^(void) {
                    [self.tableView reloadData];
                });
            });
            
        }else{
            //无收藏数据
            self.tableView.hidden = YES;
            cryview.hidden = NO;
        }
    }];
   
}

-(void)refresh{
//    sleep(2);
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
}

-(void)loadMore{
//    sleep(2);
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LZSOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[LZSOneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.Listmodel = self.dataArray[indexPath.row];
    cell.btn.hidden = YES;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

-(void)headerSdcycleScrollView{
    SDCycleScrollView *cycview = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120) delegate:self placeholderImage:[UIImage imageNamed:@"购物车界面客服热线图标.png"]];
    cycview.imageURLStringsGroup = @[@"",@"",@""];
    cycview.autoScrollTimeInterval = 2;
    cycview.autoScroll = YES;
    cycview.infiniteLoop = YES;
    self.tableView.tableHeaderView = cycview;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LZSListModel *model = self.dataArray[indexPath.row];
    LZSArticelDetailViewController *articlevc = [[LZSArticelDetailViewController alloc] init];
    articlevc.titlestr = model.title;
    articlevc.timestr = model.time;
    articlevc.srcStr = model.src;
    articlevc.content = model.content;
    [self.navigationController pushViewController:articlevc animated:YES];
}

#pragma mark=====================UITableView的删除代理================
//
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

//点击删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete){
        //在这里实现删除操作
    }
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"====");
        UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"删除后将不能找回，确认删除吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okaction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LZSListModel *model = self.dataArray[indexPath.row];
//            [[LSHttpToolsManager shareManager] PostAppUserDelMyGiftWithID:model.ID withaccess_token:self.access_token withSuccess:^(id responseObject) {
            
                //                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
                //
            

//            } WithFailure:^(NSError *error) {
//                [self showTostMessage:error.domain];
//            }];
            
            [[LZSFMDBManager fmdbManager] deleteDataWithTableName:@"news" primaryKey:model.url];
             [self.dataArray removeObjectAtIndex:indexPath.row];
             [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
            if (self.dataArray.count==0) {
                self.tableView.hidden = YES;
                self.cryview.hidden = NO;
            }else{
                self.tableView.hidden = NO;
                self.cryview.hidden = YES;
            }
            
        }];
        
        UIAlertAction *cancelaction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertvc addAction:okaction];
        [alertvc addAction:cancelaction];
        [self presentViewController:alertvc animated:YES completion:nil];
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    NSArray *arr = @[deleteAction];
    return arr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
